import pandas as pd
import numpy as np
from wordcloud import WordCloud, STOPWORDS
from PIL import Image
import matplotlib.pyplot as plt
import os
import random
import matplotlib.colors as mcolors


# ================== 艺术化配置 ==================
class Config:
    EXCEL_PATH = "clear_maded_food.xlsx"
    SHEET_NAME = "预制表格"
    OUTPUT_DIR = "艺术词云分析结果"

    # 视觉增强参数
    FONT_PATH = "msyh.ttc"
    BG_COLOR = "#FFFFFF"
    MAX_WORDS = 300
    SHAPE_IMAGE = None
    COLOR_STYLE = "gradient"  # gradient/vibrant/pastel
    CANVAS_SIZE = (1600, 800)
    ROTATE_PROB = 0.35  # 调整旋转概率 (0-1之间)

    # 动态颜色函数
    @staticmethod
    def color_func(word, font_size, position, orientation, random_state=None, **kwargs):
        if Config.COLOR_STYLE == "gradient":
            h = int(220 + position[0] / Config.CANVAS_SIZE[0] * 100)
            return f"hsl({h}, 75%, 60%)"
        elif Config.COLOR_STYLE == "vibrant":
            return random.choice(["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEEAD"])
        else:
            return f"hsl({random.randint(0, 360)}, 50%, 65%)"

    # 列配置
    COLUMNS_CONFIG = {
        'S8': 7, 'C8': 7, 'P9': 8,
        'A10': 9, 'Q7': 6
    }


# ================== 形状生成优化 ==================
def create_artistic_mask():
    width, height = Config.CANVAS_SIZE
    x, y = np.ogrid[:height, :width]

    main_plate = (x - height / 2) ** 2 / (height * 0.4) ** 2 + (y - width / 2) ** 2 / (width * 0.3) ** 2 < 1
    shadow = (x - height / 2 + 50) ** 2 / (height * 0.35) ** 2 + (y - width / 2 - 30) ** 2 / (width * 0.25) ** 2 < 1
    mask = np.where(main_plate | shadow, 0, 255).astype(np.uint8)

    for i in range(5):
        wave = np.sin(y / 30 + i * np.pi / 2) > 0.8 - i * 0.1
        mask[np.where(wave & (mask == 0))] = 127

    return Image.fromarray(mask).convert("L")


# ================== 艺术化词云生成 ==================
def artistic_wordcloud(text):
    stopwords = STOPWORDS.copy()
    stopwords.update(["进行", "主要", "各种", "包括", "使用", "通过", "需要", "要求"])

    mask = np.array(create_artistic_mask()) if not Config.SHAPE_IMAGE else np.array(Image.open(Config.SHAPE_IMAGE))

    wc = WordCloud(
        font_path=Config.FONT_PATH,
        mask=mask,
        stopwords=stopwords,
        background_color=Config.BG_COLOR,
        max_words=Config.MAX_WORDS,
        color_func=Config.color_func,
        contour_width=1,
        contour_color="gold",
        collocations=False,
        prefer_horizontal=Config.ROTATE_PROB,  # 控制旋转概率
        random_state=42,
        scale=3,
        max_font_size=200,
        min_font_size=15,
        width=Config.CANVAS_SIZE[0],
        height=Config.CANVAS_SIZE[1]
    ).generate(text)

    return wc
# ================== 可视化增强 ==================
def create_artistic_visualization(wc, col, text_count):
    plt.figure(figsize=(20, 12))

    # 改进的渲染方式
    plt.imshow(wc, interpolation="bicubic")

    # 添加艺术边框
    ax = plt.gca()
    for spine in ax.spines.values():
        spine.set_edgecolor("#FFB6C1")
        spine.set_linewidth(3)
        spine.set_linestyle(":")

    # 增强标题效果
    plt.title(f"{col} 美食元素分析",
              fontsize=24, pad=30,
              color="#FF69B4",
              fontweight="bold",
              fontstyle="italic",
              loc="left")

    plt.text(0.5, 0.95, f"共发现 {text_count} 个美食要素",
             transform=plt.gcf().transFigure,
             ha="center",
             fontsize=18,
             color="#4169E1",
             bbox=dict(boxstyle="round,pad=0.3",
                       ec="#FFB6C1",
                       fc="#FFFAF0",
                       alpha=0.8))

    plt.axis("off")
    plt.tight_layout()


# ================== 主程序 ==================
def main():
    os.makedirs(Config.OUTPUT_DIR, exist_ok=True)

    try:
        df = pd.read_excel(Config.EXCEL_PATH, sheet_name=Config.SHEET_NAME)
        print(f"数据加载成功：共 {df.shape[0]} 条记录")

        for col, start_row in Config.COLUMNS_CONFIG.items():
            if col not in df.columns:
                print(f"跳过不存在的列：{col}")
                continue

            texts = df[col].iloc[start_row:].dropna().astype(str).tolist()
            if not texts:
                print(f"跳过空列：{col}")
                continue

            # 生成词云
            wc = artistic_wordcloud(" ".join(texts))

            # 保存输出
            output_base = os.path.join(Config.OUTPUT_DIR, f"{col}_艺术分析")
            wc.to_file(f"{output_base}.png")

            # 生成预览图
            create_artistic_visualization(wc, col, len(texts))
            plt.savefig(f"{output_base}_装饰版.jpg",
                        dpi=300,
                        bbox_inches="tight",
                        quality=95)
            plt.close()

            print(f"成功生成：{col}（独特元素：{len(set(texts))}）")

    except Exception as e:
        print(f"处理异常：{str(e)}")
    finally:
        print("\n分析结果已保存至：", os.path.abspath(Config.OUTPUT_DIR))


if __name__ == "__main__":
    main()